//
//  JZBundle.swift
//
//
//  Created by S JZ on 2023/12/6.
//
 
import Foundation

import UIKit

/**
 * 获取Bundle中的图片
 * 如果为NSObject或者其子类，可以直接使用
 * 如果不为NSObject或者其子类，需要使用JZBundle
 */
public extension NSObject {
    // 获取当前Bundle
    @objc public func currentBundle() -> Bundle { Bundle(for: Self.self) }

    /// 获取当前Bundle中的图片
    /// - Parameter name: 图片名称
    /// - Returns: 生成的图片
    @objc public func bundleImage(_ name: String) -> UIImage {
        let bundle = currentBundle()
        
        guard let image = UIImage(named: name, in: bundle, compatibleWith: nil) else {
            if let path = bundle.path(forResource: name, ofType: nil),
                let image = UIImage(contentsOfFile: path) {
                return image
            }else {
                let image = UIImage(named: name)
                return image ?? UIImage()
            }
        }
        return image
    }

    /// 根据颜色名称生成图片
    /// - Parameter name: 颜色名称
    /// - Returns: 生成的颜色
    @objc public func bundleColor(_ name: String) -> UIColor {
        let bundle = currentBundle()
        guard let color = UIColor(named: name, in: bundle, compatibleWith: nil) else {
            return UIColor(named: name) ?? UIColor.clear
        }
        return color
    }
}

public protocol JZBundle where Self: AnyObject { }
public extension JZBundle {
    // 获取当前Bundle
    func currentBundle() -> Bundle { Bundle(for: Self.self) }
    
    /// 获取当前Bundle中的图片
    /// - Parameter name: 图片名称
    /// - Returns: 生成的图片
    func bundleImage(_ name: String) -> UIImage {
        let bundle = currentBundle()
        
        guard let image = UIImage(named: name, in: bundle, compatibleWith: nil) else {
            if let path = bundle.path(forResource: name, ofType: nil),
               let image = UIImage(contentsOfFile: path) {
                return image
            }else {
                let image = UIImage(named: name)
                return image ?? UIImage()
            }
        }
        return image
    }
    
    /// 根据颜色名称生成图片
    /// - Parameter name: 颜色名称
    /// - Returns: 生成的颜色
    func bundleColor(_ name: String) -> UIColor {
        let bundle = currentBundle()
        guard let color = UIColor(named: name, in: bundle, compatibleWith: nil) else {
            return UIColor(named: name) ?? UIColor.clear
        }
        return color
    }
}

